/*
 * Copyright (C), 2002-2018, Caljm有限公司
 * FileName: EchoClientHandler
 * Author:   Byron Wang
 * Date:     2018/10/29 下午11:20
 * Description: //模块目的、功能描述
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */

package com.cpcs.msgpack;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Random;

/**
 * 功能描述：
 *
 * @author Byron Wang
 * @since 2018/10/29
 */
public class MsgPackClientHandler extends SimpleChannelInboundHandler<Object> {

    private int counter;

    private int sendNumber;

    public MsgPackClientHandler(int sendNumber) {
        this.sendNumber = sendNumber;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Receive message: " + msg + ", COUNTER: " + (++counter));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        UserInfo[] infos = buildUserInfo();
        for (UserInfo info : infos) {
            System.out.println("send:" + info);
            ctx.write(info);
        }
//        ctx.write("abc");
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    private UserInfo[] buildUserInfo() {
        UserInfo[] infos = new UserInfo[sendNumber];
        Random random = new Random();
        for (int i = 0; i < sendNumber; i++) {
            UserInfo info = new UserInfo(i, "Wang" + String.valueOf(i), random.nextInt(50) + i);
            infos[i] = info;
        }
        return infos;
    }

}
